import * as types from './mutation-types';
import {playMode} from "common/js/config";
import {shuffle} from "common/js/util";

function findIndex(list,song) {
  return list.findIndex((item) => {
    return item.id === song.id
  })
}

export const selectPlay = function ({commit,state},{list,index}) {
  commit(types.SET_SEQUENCE_LIST,list);
  if (state.mode === playMode.random) {
    // 如果是从顶部随机播放进来
    let randomList = shuffle(list);
    commit(types.SET_PLAYLIST,randomList);
    // 从播放列表返回 点击歌曲列表里的歌曲
    // randomList 打乱后的歌曲列表  list[index] === 歌曲列表对应的当前歌曲
    index = findIndex(randomList,list[index]);
  } else {
    // 顺序播放的
    commit(types.SET_PLAYLIST,list);
  }
  commit(types.SET_CURRENT_INDEX,index);
  commit(types.SET_FULL_SCREEN,true);
  commit(types.SET_PLAYING_STATE,true);
};



export const randomPlay = function ({commit},{list}) {
  commit(types.SET_PLAY_MODE,playMode.random);
  commit(types.SET_SEQUENCE_LIST,list);
  let randomList = shuffle(list);
  commit(types.SET_PLAYLIST,randomList);
  commit(types.SET_CURRENT_INDEX, 0);
  commit(types.SET_FULL_SCREEN,true);
  commit(types.SET_PLAYING_STATE, true);
};


export const deleteSong = function ({commit,state},song) {
  let playlist = state.playlist.slice();
  let sequenceList = state.sequenceList.slice();
  let currentIndex = state.currentIndex;
  let pIndex = findIndex(playlist,song);
  playlist.splice(pIndex,1);
  let sIndex = findIndex(sequenceList,song);
  sequenceList.splice(sIndex,1);
  if (currentIndex > pIndex || currentIndex === playlist.length) {
    currentIndex--
  }
  commit(types.SET_PLAYLIST,playlist);
  commit(types.SET_SEQUENCE_LIST,sequenceList);
  commit(types.SET_CURRENT_INDEX,currentIndex);
  if (!playlist.length) {
    commit(types.SET_PLAYING_STATE,false)
  } else {
    commit(types.SET_PLAYING_STATE,true)
  }


}
